package code.concurrent;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureDemo {
    // 模拟三个异步执行的方法
    private static CompletableFuture<Boolean> asyncMethod1() {
        return CompletableFuture.supplyAsync(()->{
            // 模拟一些异步操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            // 假设这个方法执行成功
            return true;
        });
    }

    private static CompletableFuture<Boolean> asyncMethod2() {
        return CompletableFuture.supplyAsync(() -> {
            // 模拟一些异步操作
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            // 假设这个方法执行失败
            return false;
        });
    }

    private static CompletableFuture<Boolean> asyncMethod3() {
        return CompletableFuture.supplyAsync(() -> {
            // 模拟一些异步操作
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            // 假设这个方法执行失败
            return false;
        });
    }

    public static void main(String[] args) {
        // 并发调用三个方法
        CompletableFuture<Void> allTasks = CompletableFuture.allOf(
                asyncMethod1().thenAccept(result -> System.out.println("Method 1 success: " + result)),
                asyncMethod2().thenAccept(result -> System.out.println("Method 2 success: " + result)),
                asyncMethod3().thenAccept(result -> System.out.println("Method 3 success: " + result))
        );

        // 使用anyOf来等待任何一个CompletableFuture完成
        CompletableFuture<Object> anyTask = CompletableFuture.anyOf(
                asyncMethod1(),
                asyncMethod2(),
                asyncMethod3()
        );

        // 等待任一任务完成，并获取结果
        try {
            Object result = anyTask.get();
            if (Boolean.TRUE.equals(result)) {
                System.out.println("Any method succeeded!");
            } else {
                // 等待所有任务完成，以确保所有方法都执行完毕
                allTasks.get();
                System.out.println("All methods failed!");
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
}
